<?php
declare (strict_types=1);

namespace app\course\model\coupon\admin;

use app\common\helper\util\SnowFlake;
use app\common\model\BaseModel;
use think\helper\Str;
use think\model\relation\BelongsTo;

/**
 * 线下卡券模型
 */
class CouponOffline extends BaseModel
{
    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'coupon_offline';
    protected $append = ['status_text'];
    /**
     * 设置自动写入时间
     *
     * @var boolean
     */
    protected $autoWriteTimestamp = true;
    /**
     * 时间显示格式
     *
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';

    protected static $couponPrefix = [
        1 => 'StYhQ', // 优惠券
        2 => 'StDzK', // 打折卡
        3 => 'StKcK', // 课程卡
    ];

    public function getStatusTextAttr($value, $data): string
    {
        $text = [
            0 => '未使用',
            1 => '已使用',
            2 => '已生成订单',
        ];

        return $text[$data['status']];
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-13
     *
     * @param    [type]                         $coupon [description]
     */
    public static function onBeforeInsert($model)
    {
        // 卡号生成
        $model->offline_code = self::$couponPrefix[$model->coupon_type] . app(SnowFlake::class)->nextId() . Str::random(8);
        unset($model->coupon_type);
    }

    /**
     * 卡券领取的用户
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-08-21
     */
    public function couponUser(): BelongsTo
    {
        return $this->belongsTo(CouponUser::class, 'code', 'code')->with(['user']);
    }

    /**
     * 关联优惠券
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/11
     *
     * @return BelongsTo
     */
    public function couponMinus(): BelongsTo
    {
        return $this->belongsTo(Coupon::class, 'coupon_id')->bind(['use_stime', 'use_etime', 'maxprice', 'price']);
    }

    /**
     * 关联打折卡
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/11
     *
     * @return BelongsTo
     */
    public function couponDiscount(): BelongsTo
    {
        return $this->belongsTo(Coupon::class, 'coupon_id')->bind(['use_stime', 'use_etime', 'discount']);
    }

    /**
     * 关联课程卡
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/11
     *
     * @return BelongsTo
     */
    public function couponCourse(): BelongsTo
    {
        return $this->belongsTo(Coupon::class, 'coupon_id')->with(['course_title'])->bind(['use_stime', 'use_etime', 'course_title', 'course_id', 'course_type']);
    }
}
